/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2013-3-7         xingkong207
 */

package com.skyworth.tvos.ipcservice;

import android.content.Intent;
import android.util.Log;

import com.skyworth.framework.skysdk.ipc.SkyContext;
import com.skyworth.tvos.checker.CheckerManager;
import com.skyworth.tvos.checker.SkyServiceMoniter;
import com.skyworth.tvos.utils.IPCConst;
import com.skyworth.tvos.utils.SkyAppService;

import java.util.ArrayList;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author wei li
 * @version TODO (write something)
 * @ClassName ServiceDispatch
 * @Description TODO (write something)
 * @date 2013-3-7
 */
public class ServiceDispatch {

    public static ServiceDispatch instance = null;

    public static ServiceDispatch getInstance() {
        if (instance == null) {
            instance = new ServiceDispatch();
        }
        return instance;
    }

    public static String currentBootService = "";
    private ArrayList<SkyPackage> bootQueue = new ArrayList<SkyPackage>();
    private static String[][] packages = {
            // {SKY_SERVICE.SKY_MODULE_SYSTEM_SERVICE.toString(),"com.skyworth.service.systemservice",
            // "1"},
            // {SKY_SERVICE.SKY_MODULE_UIVIEW_SERVICE.toString(),"com.skyworth.service.uilogicservice",
            // "0.5f", "fixed"},
            // {SKY_SERVICE.SKY_MODULE_MEDIA_SERVICE.toString(),"com.skyworth.service.mediaservice",
            // "0.5f", "fixed"},
            // {SKY_SERVICE.SKY_MODULE_UIVIEW_SERVICE.toString(),"com.skyworth.service.uiviewservice",
            // "0.5f", "fixed"},
            // {SKY_SERVICE.SKY_MODULE_NET_SERVICE.toString(),"com.skyworth.tvos.netservice",
            // "0.5f", "fixed"},
            // {SKY_SERVICE.SKY_MODULE_TV_SERVICE.toString(),"com.skyworth.tvos.tvservice",
            // "0.5f", "fixed"},
            // {SKY_SERVICE.SKY_MODULE_USER_SERVICE.toString(),"com.skyworth.tvos.userservice",
            // "0.5f", "fixed"},
            // {SKY_SERVICE.SKY_MODULE_INFO_SERVICE.toString(),"com.skyworth.tvos.infoservice",
            // "0.5f", "possible"},
            // {SKY_SERVICE.SKY_MODULE_SEARCH_SERVICE.toString(),"com.skyworth.tvos.searchservice",
            // "10f", "fixed"},
            // {SKY_SERVICE.SKY_MODULE_HOMEPAGE.toString(),"com.skyworth.tvos.yzhomepage",
            // "0.5f","possible"},
            // {SKY_SERVICE.SKY_MODULE_SERVICE_SEND.toString(),"com.skyworth.tvos.screenservice",
            // "0.5f","possible"},
            // {SKY_SERVICE.SKY_MODULE_PUSH_SERVICE.toString(),"com.skyworth.tvos.pushservice",
            // "1.0f", "fixed"},
            // {SKY_SERVICE.SKY_MODULE_DE_SERVICE.toString(),"com.skyworth.tvos.deservice",
            // "0.5f", "fixed"},
            // {SKY_SERVICE.SKY_MODULE_SUI_SERVICE.toString(),"com.skyworth.tvos.suiservice",
            // "1.0f", "fixed"},
            // {SKY_SERVICE.SKY_MODULE_LOADER_SERVICE.toString(),"com.skyworth.tvos.loaderservice",
            // "1.0f", "possible"},
            {"DEServiceFreeRunning", "com.tianci.de", "1.0f", "possible"}};

    public void init() {

        SkyPackage spkg = null;
        for (int i = 0; i < packages.length; i++) {
            spkg = new SkyPackage(packages[i][0], packages[i][1],
                    Float.valueOf(packages[i][2]), packages[i][3]);
            bootQueue.add(spkg);
        }

        // try{
        // SkyServiceDocument sdoc = new
        // SkyServiceDocument("/skydir/config/bootQueue.xml");
        // ArrayList<Object> packs = sdoc.getItemsByName("package");
        // for (Object obj : packs)
        // {
        // bootQueue.add((SkyPackage)obj);
        // }
        // }catch(Exception e){
        // e.printStackTrace();
        // }
    }

    public void startService(final String service) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                currentBootService = service;
                Log.i(IPCConst.TAG, "start next service=" + service);
                SkyContext.context.startService(new Intent(service));
            }
        }).start();
    }

    public void startServices() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                SkyAppService appService = SkyAppService
                        .getInstance(SkyContext.context);
                // TODO Auto-generated method stub
                for (int i = 0; i < bootQueue.size(); i++) {
                    try {
                        // 首先判断此package是否是一定存在的service，若为可能存在（possible）的，则先判断是否有此包名的程序
                        if (bootQueue.get(i).fixType.equals(FixType.possible)) {
                            if (!appService.getAppExist(bootQueue.get(i).packageName)) {
                                continue;
                            }
                        }
                        if (bootQueue.get(i).packageName != null
                                && !bootQueue.get(i).packageName.equals("")) {
                            startService(bootQueue.get(i).packageName);
                            if (bootQueue.get(i).packageName
                                    .contains("uilogic")) {
                                // startControlReceiverTimer();
                            }
                        }
                        long delay = (long) (bootQueue.get(i).delay * 1000);
                        Log.i(IPCConst.TAG, "***bootQueue.get(i) delay="
                                + delay);
                        Thread.sleep(delay);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                CheckerManager.getChecker().addTask(
                        new SkyServiceMoniter(5, "Service moniter", bootQueue));
            }
        }).start();

    }

    public static enum FixType {
        fixed, // 一定存在的程序
        possible, // 可能存在的程序
    }

    public static class SkyPackage {
        public String serviceName = "";
        public String packageName = "";
        public float delay = 1;
        public FixType fixType = FixType.fixed;
        public int maxCheckTimes = Integer.MAX_VALUE;
        public int hasStartedTimes = 0;

        public SkyPackage() {

        }

        public SkyPackage(String sName, String pName, float delay, String type) {
            this.serviceName = sName;
            this.packageName = pName;
            this.delay = delay;
            try {
                this.fixType = FixType.valueOf(type);
            } catch (Exception e) {
            }
        }

        public SkyPackage(String sName, String pName, float delay, String type,
                          int checktimes) {
            this(sName, pName, delay, type);
            this.maxCheckTimes = checktimes;
        }
    }

    static Runnable scheduleRunable = new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            Intent intent = new Intent();
            intent.setAction("com.android.sky.SendHotKey");
            int SKY_BROADCAST_KEY_VOLUME_ADD = 0x18;// 音量加,24
            // int SKY_BROADCAST_KEY_VOLUME_REDUCE = 0x19;//音量减,25
            intent.putExtra("specialKey", SKY_BROADCAST_KEY_VOLUME_ADD);
            Log.d("eventhandler",
                    "ipc send broadcast.time=" + System.currentTimeMillis());
            SkyContext.context.sendBroadcast(intent);
            // if(receivePushCmdTimer != null){
            // receivePushCmdTimer.shutdown();
            // receivePushCmdTimer = null;
            // }
        }
    };

    static ScheduledThreadPoolExecutor receivePushCmdTimer = null;

    private static void startControlReceiverTimer() {
        receivePushCmdTimer = new ScheduledThreadPoolExecutor(1);
        receivePushCmdTimer.scheduleAtFixedRate(scheduleRunable, 240, 240,
                TimeUnit.MILLISECONDS);
    }
}
